Introducción¶

En esta prÔctica vamos a entrenar varios clasificadores sobre un mismo dataset, usando todos los algoritmos de clasificación que hemos visto hasta ahora e implementÔndolos usando las librerías adecuadas.

Dataset¶

El dataset que usaremos es "Breast Cancer Wisconsin (Diagnostic)", disponible en UCI Machine Learning Repository TambiƩn estƔ disponible directamente en sklearn.datasets.load_breast_cancer().

Descripción del dataset

Aspecto Detalle
Tipo de problema Clasificación binaria
Objetivo Diagnosticar si un tumor es maligno (1) o benigno (0)
NĆŗmero de muestras 569
Número de variables 30 características numéricas
Balance de clases Moderadamente balanceado (~37% malignos, ~63% benignos)

Métrica¶

Elige la mƩtrica adecuada para evaluar tus modelos. Justifica tu respuesta.

El dataset no estĆ” perfectamente balanceada, por lo que accuracy puede inducir sesgos (un modelo que siempre predice ā€œbenignoā€ tendrĆ­a ~63% de acierto).

El AUC-ROC mide la capacidad discriminativa del modelo (quƩ tan bien separa positivos y negativos) independientemente del umbral, y es mƔs informativa cuando las clases son desiguales.

Es ademÔs aplicable y comparable entre modelos probabilísticos (Naïve Bayes, Regresión Logística, Redes Bayesianas) y no probabilísticos (CART).

1. Cargar el dataset e importar librerías¶

InĀ [4]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, KBinsDiscretizer
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import roc_auc_score, roc_curve, auc, confusion_matrix
InĀ [5]:
# Cargar dataset
data = datasets.load_breast_cancer()
print(data.keys())

# Separar X e y
X = data["data"]
y = data["target"]       
feature_names = data.feature_names
target_names = data.target_names
dict_keys(['data', 'target', 'frame', 'target_names', 'DESCR', 'feature_names', 'filename', 'data_module'])

Información detallada sobre el dataset:

InĀ [6]:
print(data.DESCR)
.. _breast_cancer_dataset:

Breast cancer Wisconsin (diagnostic) dataset
--------------------------------------------

**Data Set Characteristics:**

:Number of Instances: 569

:Number of Attributes: 30 numeric, predictive attributes and the class

:Attribute Information:
    - radius (mean of distances from center to points on the perimeter)
    - texture (standard deviation of gray-scale values)
    - perimeter
    - area
    - smoothness (local variation in radius lengths)
    - compactness (perimeter^2 / area - 1.0)
    - concavity (severity of concave portions of the contour)
    - concave points (number of concave portions of the contour)
    - symmetry
    - fractal dimension ("coastline approximation" - 1)

    The mean, standard error, and "worst" or largest (mean of the three
    worst/largest values) of these features were computed for each image,
    resulting in 30 features.  For instance, field 0 is Mean Radius, field
    10 is Radius SE, field 20 is Worst Radius.

    - class:
            - WDBC-Malignant
            - WDBC-Benign

:Summary Statistics:

===================================== ====== ======
                                        Min    Max
===================================== ====== ======
radius (mean):                        6.981  28.11
texture (mean):                       9.71   39.28
perimeter (mean):                     43.79  188.5
area (mean):                          143.5  2501.0
smoothness (mean):                    0.053  0.163
compactness (mean):                   0.019  0.345
concavity (mean):                     0.0    0.427
concave points (mean):                0.0    0.201
symmetry (mean):                      0.106  0.304
fractal dimension (mean):             0.05   0.097
radius (standard error):              0.112  2.873
texture (standard error):             0.36   4.885
perimeter (standard error):           0.757  21.98
area (standard error):                6.802  542.2
smoothness (standard error):          0.002  0.031
compactness (standard error):         0.002  0.135
concavity (standard error):           0.0    0.396
concave points (standard error):      0.0    0.053
symmetry (standard error):            0.008  0.079
fractal dimension (standard error):   0.001  0.03
radius (worst):                       7.93   36.04
texture (worst):                      12.02  49.54
perimeter (worst):                    50.41  251.2
area (worst):                         185.2  4254.0
smoothness (worst):                   0.071  0.223
compactness (worst):                  0.027  1.058
concavity (worst):                    0.0    1.252
concave points (worst):               0.0    0.291
symmetry (worst):                     0.156  0.664
fractal dimension (worst):            0.055  0.208
===================================== ====== ======

:Missing Attribute Values: None

:Class Distribution: 212 - Malignant, 357 - Benign

:Creator:  Dr. William H. Wolberg, W. Nick Street, Olvi L. Mangasarian

:Donor: Nick Street

:Date: November, 1995

This is a copy of UCI ML Breast Cancer Wisconsin (Diagnostic) datasets.
https://goo.gl/U2Uwz2

Features are computed from a digitized image of a fine needle
aspirate (FNA) of a breast mass.  They describe
characteristics of the cell nuclei present in the image.

Separating plane described above was obtained using
Multisurface Method-Tree (MSM-T) [K. P. Bennett, "Decision Tree
Construction Via Linear Programming." Proceedings of the 4th
Midwest Artificial Intelligence and Cognitive Science Society,
pp. 97-101, 1992], a classification method which uses linear
programming to construct a decision tree.  Relevant features
were selected using an exhaustive search in the space of 1-4
features and 1-3 separating planes.

The actual linear program used to obtain the separating plane
in the 3-dimensional space is that described in:
[K. P. Bennett and O. L. Mangasarian: "Robust Linear
Programming Discrimination of Two Linearly Inseparable Sets",
Optimization Methods and Software 1, 1992, 23-34].

This database is also available through the UW CS ftp server:

ftp ftp.cs.wisc.edu
cd math-prog/cpo-dataset/machine-learn/WDBC/

.. dropdown:: References

  - W.N. Street, W.H. Wolberg and O.L. Mangasarian. Nuclear feature extraction
    for breast tumor diagnosis. IS&T/SPIE 1993 International Symposium on
    Electronic Imaging: Science and Technology, volume 1905, pages 861-870,
    San Jose, CA, 1993.
  - O.L. Mangasarian, W.N. Street and W.H. Wolberg. Breast cancer diagnosis and
    prognosis via linear programming. Operations Research, 43(4), pages 570-577,
    July-August 1995.
  - W.H. Wolberg, W.N. Street, and O.L. Mangasarian. Machine learning techniques
    to diagnose breast cancer from fine-needle aspirates. Cancer Letters 77 (1994)
    163-171.

Veamos cómo son las clases:

InĀ [7]:
print(data.target_names)

print(np.unique(data.target))
['malignant' 'benign']
[0 1]

Por lo tanto, este dataset no sigue la convención usual y tenemos que:

0 -> 'malignant'

1 -> 'benign'

InĀ [8]:
# Cargar como dataframe, con y en la columna llamada 'target'
df = pd.DataFrame(data=data["data"], columns=data["feature_names"])
df["target"] = y

print("Clase (counts):")
print(df['target'].value_counts())
Clase (counts):
target
1    357
0    212
Name: count, dtype: int64

2. AnÔlisis exploratorio¶

InĀ [9]:
df.columns
Out[9]:
Index(['mean radius', 'mean texture', 'mean perimeter', 'mean area',
       'mean smoothness', 'mean compactness', 'mean concavity',
       'mean concave points', 'mean symmetry', 'mean fractal dimension',
       'radius error', 'texture error', 'perimeter error', 'area error',
       'smoothness error', 'compactness error', 'concavity error',
       'concave points error', 'symmetry error', 'fractal dimension error',
       'worst radius', 'worst texture', 'worst perimeter', 'worst area',
       'worst smoothness', 'worst compactness', 'worst concavity',
       'worst concave points', 'worst symmetry', 'worst fractal dimension',
       'target'],
      dtype='object')
InĀ [10]:
# Histograma por clase

sns.countplot(data=df, x="target")
INFO:matplotlib.category:Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.
INFO:matplotlib.category:Using categorical units to plot a list of strings that are all parsable as floats or dates. If these strings should be plotted as numbers, cast to the appropriate data type before plotting.
Out[10]:
<Axes: xlabel='target', ylabel='count'>
No description has been provided for this image
InĀ [11]:
# Histogramas de algunas variables por clase

columns_histogram = ["mean radius", "mean symmetry", "radius error", "symmetry error", "worst radius", "worst symmetry"]

for c in columns_histogram:
    sns.histplot(data=df,
                 x=df[c],
                 hue=df["target"])
    plt.show()
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
No description has been provided for this image
InĀ [12]:
# Todos los pairplots posibles, segmentados por clase.
# Usa Seaborn pairplot

sns.pairplot(data=df, hue="target")
Out[12]:
<seaborn.axisgrid.PairGrid at 0x19fc7918a90>
No description has been provided for this image
InĀ [13]:
# EstadĆ­sticas descriptivas
print(df.describe().T[['mean', 'std', 'min', 'max']])
                               mean         std         min         max
mean radius               14.127292    3.524049    6.981000    28.11000
mean texture              19.289649    4.301036    9.710000    39.28000
mean perimeter            91.969033   24.298981   43.790000   188.50000
mean area                654.889104  351.914129  143.500000  2501.00000
mean smoothness            0.096360    0.014064    0.052630     0.16340
mean compactness           0.104341    0.052813    0.019380     0.34540
mean concavity             0.088799    0.079720    0.000000     0.42680
mean concave points        0.048919    0.038803    0.000000     0.20120
mean symmetry              0.181162    0.027414    0.106000     0.30400
mean fractal dimension     0.062798    0.007060    0.049960     0.09744
radius error               0.405172    0.277313    0.111500     2.87300
texture error              1.216853    0.551648    0.360200     4.88500
perimeter error            2.866059    2.021855    0.757000    21.98000
area error                40.337079   45.491006    6.802000   542.20000
smoothness error           0.007041    0.003003    0.001713     0.03113
compactness error          0.025478    0.017908    0.002252     0.13540
concavity error            0.031894    0.030186    0.000000     0.39600
concave points error       0.011796    0.006170    0.000000     0.05279
symmetry error             0.020542    0.008266    0.007882     0.07895
fractal dimension error    0.003795    0.002646    0.000895     0.02984
worst radius              16.269190    4.833242    7.930000    36.04000
worst texture             25.677223    6.146258   12.020000    49.54000
worst perimeter          107.261213   33.602542   50.410000   251.20000
worst area               880.583128  569.356993  185.200000  4254.00000
worst smoothness           0.132369    0.022832    0.071170     0.22260
worst compactness          0.254265    0.157336    0.027290     1.05800
worst concavity            0.272188    0.208624    0.000000     1.25200
worst concave points       0.114606    0.065732    0.000000     0.29100
worst symmetry             0.290076    0.061867    0.156500     0.66380
worst fractal dimension    0.083946    0.018061    0.055040     0.20750
target                     0.627417    0.483918    0.000000     1.00000
InĀ [14]:
# Matriz de correlaciones entre las variables
# Para calcular las correlaciones necesitas la función `corr``

correlaciones = df.corr(numeric_only=True)

plt.figure(figsize=(12,12))
sns.heatmap(
    data=correlaciones,
    annot=True,
    annot_kws={"fontsize":7},
    fmt=".1f",
)
plt.xticks(fontsize=6)
plt.yticks(fontsize=6)
plt.show()
No description has been provided for this image
InĀ [15]:
# Top correlaciones con el target

df_correlaciones = pd.DataFrame(correlaciones)

df_correlaciones_target = df_correlaciones["target"].sort_values(ascending=True).reset_index()

plt.figure(figsize=(12,12))
sns.heatmap(
    data=df_correlaciones_target.set_index("index"),
    annot=True,
    annot_kws={"fontsize":14},
    fmt=".5f"
)
plt.xticks(fontsize=10)
plt.yticks(fontsize=10)
plt.show()
No description has been provided for this image

3. Separación train/test¶

InĀ [16]:
# Config reproducible
RANDOM_STATE = 42
np.random.seed(RANDOM_STATE)
InĀ [17]:
from sklearn.model_selection import train_test_split
InĀ [36]:
# Separa train y test ysando la función adecuada de scikit-learn.
# Usa el parƔmetro random_state=RANDOM_STATE para controlar la aleatoriedad
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.67, random_state=RANDOM_STATE, stratify=y)

La regresión logística se entrena mediante descenso del gradiente, y la escala de las variables afecta la velocidad y estabilidad numérica del entrenamiento. Si las variables tienen órdenes de magnitud distintos, los gradientes también lo tendrÔn, y el proceso puede converger mal o lentamente.

Por este motivo, estandariza los datos usando StandardScaler —es decir, restar la media y dividir por la desviación tĆ­pica.

InĀ [52]:
scaler = StandardScaler()
X_train_std = scaler.fit_transform(X_train)
X_test_std = scaler.transform(X_test)

4. Entrenar modelos clÔsicos¶

Regresión logística¶

InĀ [53]:
# Usa LogisticRegression para ajustar una regresión logística

modelo = LogisticRegression(random_state=RANDOM_STATE)

modelo.fit(X_train_std, y_train)
Out[53]:
LogisticRegression(random_state=42)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
Parameters
penaltyĀ  'l2'
dualĀ  False
tolĀ  0.0001
CĀ  1.0
fit_interceptĀ  True
intercept_scalingĀ  1
class_weightĀ  None
random_stateĀ  42
solverĀ  'lbfgs'
max_iterĀ  100
multi_classĀ  'deprecated'
verboseĀ  0
warm_startĀ  False
n_jobsĀ  None
l1_ratioĀ  None
InĀ [54]:
# Realiza predicciones sobre test
y_test_hat = modelo.predict(X_test_std)

print(y_test_hat)
[1 1 0 0 0 1 1 1 1 1 1 0 0 1 1 0 1 1 0 0 1 1 1 1 1 0 1 1 1 0 1 0 0 1 1 1 1
 1 1 1 1 1 1 0 1 0 1 1 1 0 1 0 1 1 0 1 0 1 1 0 1 0 0 1 1 0 1 1 1 1 1 1 1 0
 1 0 1 1 0 0 0 0 1 1 1 1 1 0 0 0 0 1 1 1 0 1 0 1 1 0 1 0 1 0 1 1 0 0 1 1 0
 1 1 0 1 0 1 1 0 1 0 1 1 1 1 1 1 0 1 0 1 0 1 1 1 0 1 0 1 0 1 1 1 1 1 0 0 0
 1 1 1 1 1 0 0 1 1 0 0 1 1 0 1 1 1 0 0 1 1 0 1 1 1 1 0 0 0 1 1 0 0 1 1 0 0
 0 1 0]

Podemos ver no sólo la clase predicha, sino la probabilidad que asigna a cada clase:

InĀ [55]:
# Usa `predict_proba``
y_test_proba = modelo.predict_proba(X_test_std)
InĀ [56]:
# CƔlculo de AUC
proba_log = modelo.predict_proba(X_test_std)[:, 1]
auc_log = roc_auc_score(y_test, proba_log)
print(f"Logistic Regression AUC: {auc_log}")
Logistic Regression AUC: 0.9984261501210654

Naive Bayes (GaussianNB)¶

InĀ [57]:
# Naive Bayes usando GaussianNB
nb_clf = GaussianNB()
nb_clf.fit(X_train_std, y_train)
proba_nb = nb_clf.predict_proba(X_test_std)[:,1]
auc_nb = roc_auc_score(y_test, proba_nb)
print(f"GaussianNB AUC: {auc_nb}")
GaussianNB AUC: 0.9915254237288135

Árbol de decisión¶

InĀ [65]:
# Árbol de decisión (CART) usando DecisionTreeClassifier
tree_clf = DecisionTreeClassifier(max_depth=8, random_state=RANDOM_STATE)
tree_clf.fit(X_train_std, y_train)

proba_tree = tree_clf.predict_proba(X_test_std)[:,1]
auc_tree = roc_auc_score(y_test, proba_tree)

print(f"CART AUC: {auc_nb}")
CART AUC: 0.9915254237288135

5. Red Bayesiana¶

Implementa la red bayesiana con pgmpy.

InĀ [66]:
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

from sklearn.preprocessing import KBinsDiscretizer
from sklearn.feature_selection import mutual_info_classif

Seleccionamos un subconjunto de features (top K) para reducir la complejidad

InĀ [67]:
K = 6

mi = mutual_info_classif(X_train, y_train, random_state=42)
top_idx = np.argsort(mi)[-K:][::-1]
top_features = feature_names[top_idx]
print("Usando estas variables para la red bayesiana:", list(top_features))
Usando estas variables para la red bayesiana: [np.str_('worst perimeter'), np.str_('worst area'), np.str_('worst radius'), np.str_('worst concave points'), np.str_('mean concave points'), np.str_('mean perimeter')]

Discretizamos estas features (KBins) usando cuantiles para mantener interpretación

InĀ [68]:
# Discretizar variables usando KBinsDiscretizer
kbd = KBinsDiscretizer(n_bins=5, encode='ordinal', strategy='quantile')
X_train_disc = kbd.fit_transform(X_train[:, top_idx])
X_test_disc = kbd.transform(X_test[:, top_idx])

# Construimos DataFrame discreto para pgmpy
cols = [f"X{i}" for i in range(K)]
df_train_bn = pd.DataFrame(X_train_disc, columns=cols)
df_train_bn["target"] = y_train.astype(int)
c:\Users\joelv\anaconda3\envs\aprendizaje_automatico\lib\site-packages\sklearn\preprocessing\_discretization.py:296: FutureWarning: The current default behavior, quantile_method='linear', will be changed to quantile_method='averaged_inverted_cdf' in scikit-learn version 1.9 to naturally support sample weight equivalence properties by default. Pass quantile_method='averaged_inverted_cdf' explicitly to silence this warning.
  warnings.warn(
InĀ [69]:
# Estructura de NaĆÆve Bayes: target -> cada feature
edges = [("target", f"X{i}") for i in range(K)]
bn_model = DiscreteBayesianNetwork(edges)

# Ajustamos los parƔmetros por mƔxima verosimilitud
bn_model.fit(df_train_bn, estimator=MaximumLikelihoodEstimator)

# Inferencia
infer = VariableElimination(bn_model)

# Predicción de probabilidades para test
def bn_predict_proba_row(row_disc):
    evidence = {f"X{i}": int(row_disc[i]) for i in range(K)}
    q = infer.query(variables=["target"], evidence=evidence, show_progress=False)
    return float(q.values[1])  # probabilidad de clase 1 (benign)

proba_bn = np.array([bn_predict_proba_row(row) for row in X_test_disc])
auc_bn = roc_auc_score(y_test, proba_bn)
print(f"AUC - Red bayesiana (NaĆÆve Bayes manual): {auc_bn:.4f}")
INFO:pgmpy: Datatype (N=numerical, C=Categorical Unordered, O=Categorical Ordered) inferred from data: 
 {'X0': 'N', 'X1': 'N', 'X2': 'N', 'X3': 'N', 'X4': 'N', 'X5': 'N', 'target': 'N'}
AUC - Red bayesiana (NaĆÆve Bayes manual): 0.9643

6. Comparación: ROC curves¶

InĀ [70]:
fpr_log, tpr_log, _ = roc_curve(y_test, proba_log)
fpr_nb, tpr_nb, _ = roc_curve(y_test, proba_nb)
fpr_tree, tpr_tree, _ = roc_curve(y_test, proba_tree)
fpr_bn, tpr_bn, _ = roc_curve(y_test, proba_bn)

plt.figure(figsize=(8,6))
plt.plot(fpr_log, tpr_log, label=f'Logistic (AUC={auc_log:.3f})')
plt.plot(fpr_nb, tpr_nb, label=f'GaussianNB (AUC={auc_nb:.3f})')
plt.plot(fpr_tree, tpr_tree, label=f'DecisionTree (AUC={auc_tree:.3f})')
plt.plot(fpr_bn, tpr_bn, label=f'BayesianNet (AUC={auc_bn:.3f})')
plt.plot([0,1], [0,1], 'k--', label='Chance')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curves Comparison')
plt.legend(loc='lower right')
plt.grid(True)
plt.show()
No description has been provided for this image
InĀ [64]:
# Resultado resumen en DataFrame

results = pd.DataFrame({
    'model': ['LogisticRegression','GaussianNB','DecisionTree','BayesianNetwork'],
    'auc': [auc_log, auc_nb, auc_tree, auc_bn]
})
print(results.sort_values('auc', ascending=False))
                model       auc
0  LogisticRegression  0.998426
1          GaussianNB  0.991525
3     BayesianNetwork  0.964286
2        DecisionTree  0.914165